package com.itguigu.glimail.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itguigu.glimail.member.entity.MemberLevelEntity;
import com.itguigu.glimail.member.exception.PhoneExistException;
import com.itguigu.glimail.member.exception.UsernameExistException;
import com.itguigu.glimail.member.vo.MemberLoginVo;
import com.itguigu.glimail.member.vo.MemberRegistVo;
import com.itguigu.glimail.member.vo.SocialUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itguigu.common.utils.PageUtils;
import com.itguigu.common.utils.Query;

import com.itguigu.glimail.member.dao.MemberDao;
import com.itguigu.glimail.member.entity.MemberEntity;
import com.itguigu.glimail.member.service.MemberService;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberDao memberDao;
    @Autowired
    RestTemplate restTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();
//        检查是否唯一 为了让controller感知异常 异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setNickname(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
//        设置默认等级
        MemberLevelEntity memberLevelEntity = memberDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());
        //密码进行盐值加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(password);
        //其他默认信息
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));

        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo loginVo) {
        String loginacct = loginVo.getLoginacct();
        String password = loginVo.getPassword();
        //去数据库查询
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("mobile", loginacct));
        if (memberEntity==null) {
            //登录失败
            return null;
        }else {
            String passwordDb = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if (matches) {
                return memberEntity;
            } else {
                return null;
            }

        }

    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws RestClientException{

        //具有登录和注册合并逻辑
        String uid = socialUser.getUid();
        MemberEntity socialMember = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        //判断用户有没有登陆过
        if (socialMember != null) {

            //这个用户注册过
            MemberEntity updater = new MemberEntity();
            updater.setId(socialMember.getId());
            updater.setAccessToken(socialUser.getAccess_token());
            updater.setExpireIn(socialUser.getExpires_in());
            memberDao.updateById(updater);
            socialMember.setAccessToken(socialUser.getAccess_token());
            socialMember.setExpireIn(socialUser.getExpires_in());
            return socialMember;

        } else {
            //如果没有登陆过  就注册
            MemberEntity memberEntity = new MemberEntity();
            //查询社交用户的社交信息
            try {
                Map<String, String> map = new HashMap<>();
                map.put("access_token", socialUser.getAccess_token());
                map.put("uid", socialUser.getUid());
                ResponseEntity<String> responseEntity = restTemplate.getForEntity("https://api.weibo.com/2/users/show.json?access_token={access_token}&uid={uid}", String.class, map);
                if (responseEntity.getStatusCode().is2xxSuccessful()) {
                    String body = responseEntity.getBody();
                    JSONObject jsonObject = JSON.parseObject(body);
                    //昵称
                    String name = jsonObject.getString("name");
                    //性别
                    String gender = jsonObject.getString("gender");
                    memberEntity.setNickname(name);
                    memberEntity.setGender("m".equals(gender) ? 1 : 0);
                    memberEntity.setAccessToken(socialUser.getAccess_token());
                    memberEntity.setExpireIn(socialUser.getExpires_in());
                    memberEntity.setSocialUid(socialUser.getUid());

                }
            } catch (RestClientException e) {

            }
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpireIn(socialUser.getExpires_in());
            memberEntity.setSocialUid(socialUser.getUid());
            memberDao.insert(memberEntity);
            return memberEntity;
        }

    }

}
